package com.stn.zjx.givingtreasure.activity.set;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.userlogin.UserPassResetThreeActivity;
import com.stn.zjx.givingtreasure.activity.userlogin.UserPassResetTwoActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.domain.UserProfileDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.QQWeixinNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.RxRegTool;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class UserPhoneBindActivity extends BaseActivity {


    //正在发送中
    boolean isSendLoading = false;
    int seconds = 60;
    EventHandler eh;
    Disposable sendvalidate__disposable = null;
    private String phone = "";
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.left_star)
    TextView leftStar;
    @BindView(R.id.phone_edit)
    EditText phoneEdit;
    @BindView(R.id.phone_tv)
    TextView phoneTv;
    @BindView(R.id.validate_bt)
    TextView validateBt;
    @BindView(R.id.validate_edit)
    EditText validateEdit;
    @BindView(R.id.phone_ll)
    LinearLayout phoneLl;
    @BindView(R.id.next_bt)
    ButtonBgUi nextBt;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.bind_phone));
        validateBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!RxNetTool.isAvailable(getApplicationContext())) {
                    showToast(getString(R.string.request_networkavailable));
                    return;
                }
                if (TextUtils.isEmpty(phoneEdit.getText().toString().trim())) {
                    showToast(getString(R.string.phone_isnotempty));
                    return;
                }
                if (!RxRegTool.isMobile(phoneEdit.getText().toString().trim())) {
                    showToast(getString(R.string.please_isnotreal_phone));
                    return;
                }
                sendValidate();
                SMSSDK.getVerificationCode("86", "" + phoneEdit.getText().toString().trim());

            }
        });

        eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {

                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(UserService.getInstance(getApplicationContext())
                                        .getOnlineLoginUser()==null){

                                    return;
                                }

                                relation(phoneEdit.getText().toString(),0,
                                        UserService.getInstance(getApplicationContext())
                                                .getOnlineLoginUser().getToken());
                            }
                        });
                        //提交验证码成功
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {


                                showToast(getString(R.string.sms_send_wait));
                            }
                        });

                    }
                } else {

                    runOnUiThread(() -> {
                        String str = ((Throwable) data).getMessage();
                        try {
                            JSONObject jb = new JSONObject(str);
                            showToast(jb.getString("detail"));

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    });
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eh); //注册短信回调
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_phone_bind);
        ButterKnife.bind(this);
        initComponent();
    }

    @OnClick({R.id.back_bt, R.id.action_title,R.id.next_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.next_bt:
                if (TextUtils.isEmpty(validateEdit.getText().toString().trim())) {
                    showToast(getString(R.string.sms_isnotempty));
                    return;
                }
                if (!RxNetTool.isAvailable(this)) {
                    showToast(getString(R.string.request_networkavailable));
                    return;
                }
                SMSSDK.submitVerificationCode("86", phoneEdit.getText().toString().trim(),
                        validateEdit.getText().toString().trim());
                break;

        }
    }



    //发送短信验证
    public void sendValidate() {
        sendvalidate__disposable = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> observableEmitter) {
                while (isSendLoading && seconds > 0) {
                    seconds--;
                    observableEmitter.onNext(seconds);
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        sendvalidate__disposable.dispose();
                        e.printStackTrace();
                    }
                }
                observableEmitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        isSendLoading = true;
                        validateBt.setBackgroundResource(R.drawable.round_darkgray_bg);
                        validateBt.setClickable(false);

                    }
                })
                .subscribe(new Consumer<Integer>() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void accept(Integer seconds) {
                        isSendLoading = true;
                        validateBt.setText(getString(R.string.surplus)
                                + "" + seconds + getString(R.string.seconds)
                                + getString(R.string.resend));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        sendvalidate__disposable.dispose();
                        reset_sendValidate();
                    }
                }, new Action() {
                    @Override
                    public void run() {
                        reset_sendValidate();
                    }
                });


    }

    //重置发送短信按钮
    public void reset_sendValidate() {
        isSendLoading = false;
        validateBt.setText(getString(R.string.get_validate));
        validateBt.setBackgroundResource(R.drawable.round_default_theme_bg);
        seconds = 60;
        validateBt.setClickable(true);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sendvalidate__disposable != null) {
            sendvalidate__disposable.dispose();
            reset_sendValidate();
        }
        SMSSDK.unregisterEventHandler(eh);
    }
    public void relation(String phone,Integer type,String token){
        QQWeixinNetImpl
                .qqweixin_third_relation("",phone,type, token, "qqweixin_third_relation", new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        showLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        dissmissLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        StatusDomain domain=new Gson().fromJson(response.body(),StatusDomain.class);
                        switch (domain.getStatus()){
                            case BaseApi.REQUEST_SUCCESS_CODE:
                                 User user=UserService
                                         .getInstance(getApplicationContext())
                                         .getOnlineLoginUser();
                                 user.setUserPhone(phone);
                                 UserService.getInstance(getApplicationContext())
                                         .updateUser(user);
                                 finish();
                                break;
                            default:

                                break;
                        }
                        showToast(domain.getMessage());
                    }
                });
    }







}
